#规范化文件名，统一化文件名，重命名
import os
from tqdm import tqdm
dir2 = "/media/liyan/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司/YOLOv4_data/darknet-master/traffic_light/train/img"
dir1 = "/media/liyan/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司/YOLOv4_data/darknet-master/traffic_light/train/xml"

delete_list = []
renamed1_dict = {}
renamed2_dict = {}
file_names1 = os.listdir(dir1)
file_names2 = os.listdir(dir2)


for index1,name1 in tqdm(enumerate(file_names1),ncols=100,total=len(file_names1)):
    baseName1 = ''.join(name1.split(".")[:-1])
    name1_path = os.path.join(dir1,name1)
    # postfix_name1 = "."+name1.split(".")[-1]
    for index2,name2 in enumerate(file_names2):
        baseName2 = ''.join(name2.split(".")[:-1])
        # name2_path = os.path.join(dir2,name2)
        # postfix_name2 = "."+name2.split(".")[-1]

        flag = False
        if baseName2 == baseName1:
            # rename = str(index1)+str(index2)
            # renamed1_dict[name1] = rename+postfix_name1
            # renamed2_dict[name2] = rename+postfix_name2
            flag = True
            break
    if not flag:            #dir1的文件是否在dir2中也存在，如果不存在，则删除，用来确保两个文件夹里的文件前缀名是一一对应的
        delete_list.append(name1_path)


for k,v in renamed2_dict.items():
    os.rename(os.path.join(dir2,k),os.path.join(dir2,v))
for k,v in renamed1_dict.items():
    os.rename(os.path.join(dir1,k),os.path.join(dir1,v))
for i in delete_list:
    os.remove(i)
